
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.PinYinHelper;
import com.jf.cloud.service.sysmanager.common.util.RandomUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.MatchConstant;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 员工控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appPubgUser")
public class AppPubgUserController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgUserController.class);

	/**
	 * 员工服务
	 */
	@Resource
	private IPubgUserService pubgUserService;

	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgUserTeamService pubgUserTeamService;
	
	@Resource
	private IPubgMatchService pubgMatchService;

	@Resource
	private IPubgUserMatchService pubgUserMatchService;
	
	@Resource
	private TokenHandler tokenHandler;
	
	@Resource
	private IPubgOperateLogService pubgOperateLogService;

	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;
	
	/**
	 * 用户详情
	 * 
	 * @author 代码机1.0 创建时间：2018-03-31
	 */
	@ResponseBody
	@RequestMapping("/userDetail")
	public Result<Map<String, Object>> listPubgUserData(String token, HttpServletRequest request) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("用户详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
            if (userId == null || userId.trim().length() == 0) {
                result.setCode(-2);
                result.setMessage("请重新登陆！");
                return result;
            }
            
            Map<String, Object> data = this.pubgUserService.getUserInfo(Long.valueOf(userId));
            String userAccount = data.get("userAccount").toString();
            data.put("userAccount", userAccount.subSequence(0, 3) + "****" + userAccount.substring(8));
            result.setData(data);
            result.setCode(0);
            result.setMessage("获取用户详情成功！");
		} catch (Exception e) {
			log.error("用户详情出错！", e);
		}
		return result;
	}

	/**
	 * 更新用户信息
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 下午1:13:11
	 */
	@ResponseBody
	@RequestMapping("/updateUserInfo")
	public Result<String> updateUserInfo(String token, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("更新用户信息失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
			    result.setCode(-2);
			    result.setMessage("请重新登陆！");
			    return result;
			}
			
			String nickname = getParamValueString(request, "nickname");
			if (StringUtil.isNull(nickname)) {
				result.setMessage("昵称为空！");
				return result;
			}
			String nicknameInitial = nickname.substring(0, 1);
			nicknameInitial = PinYinHelper.getFirstLetter(nicknameInitial, true);
			
			String gameRole = getParamValueString(request, "gameRole");
			if (StringUtil.isNull(gameRole)) {
				result.setMessage("游戏角色为空！");
				return result;
			}
			String linkQq = getParamValueString(request, "linkQq");
			if (StringUtil.isNull(linkQq)) {
				result.setMessage("联系QQ为空！");
				return result;
			}
			PubgUser pubgUser = new PubgUser();
			pubgUser.setRowId(Long.valueOf(userId));
			pubgUser.setNickname(nickname);
			pubgUser.setNicknameInitial(nicknameInitial);
			pubgUser.setGameRole(gameRole);
			pubgUser.setLinkQq(linkQq);
			pubgUser.setInfoCompleteFlag(1);
			boolean boo = this.pubgUserService.updateUserInfo(pubgUser);
			if (boo) {
				result.setCode(0);
				result.setMessage("更新用户信息成功！");
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, "修改用户");
			}
		} catch (Exception e) {
			log.error("更新用户信息出错！", e);
		}
		return result;
	}

	/**
	 * 申请加入战队
	 * 
	 * @author 朱建文 创建时间：2018年4月2日 下午1:13:11
	 */
	@ResponseBody
	@RequestMapping("/joinTeam")
	public Result<String> joinTeam(String token, Long teamId, String inviteCode, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("加入战队失败！");
		try {
		
			// 用户token状态
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 用户角色是否为普通用户
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (!UserConstant.USER_ROLE_10.getId().equals(pubgUser.getUserRole())) {
				String role = "队长";
				if (!UserConstant.USER_ROLE_20.getId().equals(pubgUser.getUserRole())) {
					role = "部长";
				}
				result.setMessage("您当前为" + role + "，不能加入任何战队");
				return result;
			}
			
			// 验证战队是否存在
			PubgTeam pubgTeam = this.pubgTeamService.findByPK(teamId);
			if (pubgTeam == null) {
				result.setMessage("战队不存在！");
			    return result;
			}
			
			// 验证是否已经申请、已经是该战队队员
			Query query = new Query();
            query.put("USER_ID", pubgUser.getRowId());
            query.put("TEAM_ID", pubgTeam.getRowId());
            query.put("_IN$RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_1 + ", " + PubgConstant.USER_TEAM_RELATION_STATE_2);
            List<PubgUserTeam> pubgUserTeamList = pubgUserTeamService.findList(query);
            for (PubgUserTeam pubgUserTeam : pubgUserTeamList) {
				if (PubgConstant.USER_TEAM_RELATION_STATE_1.equals(pubgUserTeam.getRelationState())) {
					result.setMessage("您已经申请，勿重复申请！");
					return result;
				} else if (PubgConstant.USER_TEAM_RELATION_STATE_2.equals(pubgUserTeam.getRelationState())) {
					result.setMessage("您已经是该战队的队员！");
					return result;
				}
			}
			
			// 验证 邀请码
			int inviteFrom = 0;
			if (inviteCode == null || inviteCode.length() == 0) {
				result.setMessage("邀请码为空！");
				return result;
			}
			if (inviteCode.equals(pubgTeam.getInviteCode())) {
				inviteFrom = 1;
			}
			if (inviteFrom == 0) {
				PubgClub pubgClub = this.pubgClubService.findByPK(pubgTeam.getClubId());
				if (inviteCode.equals(pubgClub.getInviteCode())) {
					inviteFrom = 2;
				}
			}
			if (inviteFrom == 0) {
				result.setMessage("邀请码错误！");
				return result;
			}
			
			// 加入战队
			PubgUserTeam pubgUserTeam = new PubgUserTeam();
			pubgUserTeam.setInviteFrom(inviteFrom);
			pubgUserTeam.setUserId(pubgUser.getRowId());
			pubgUserTeam.setUserAccount(pubgUser.getUserAccount());
			this.pubgUserService.applyJoinTeam(pubgUserTeam, pubgTeam);
			result.setCode(0);
			result.setMessage("申请成功！");
			
			// 记录操作日志
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), null, "申请加入战队：" + pubgTeam.getTeamName());
		} catch (NumberFormatException e) {
			log.error("申请加入战队出错！", e);
		}
		return result;
	}
	
	/**
	 * 申请参加比赛
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 下午8:52:21
	 */
	@ResponseBody
	@RequestMapping("/applyJoinMatch")
	public Result<String> applyJoinMatch(Long teamId, Long matchId, HttpServletRequest request){
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("申请参加比赛失败！");
		try {
		
			// 用户token状态
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 验证队员是否普通用户
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (UserConstant.USER_ROLE_10.getId().intValue() != pubgUser.getUserRole()) {
				String role = "队长";
				if (UserConstant.USER_ROLE_30.getId().intValue() != pubgUser.getUserRole()) {
					role = "部长";
				}
				result.setMessage("您当前为" + role + "，不能加入任何比赛");
				return result;
			}
			
			// 验证战队是否存在
			PubgTeam pubgTeam = this.pubgTeamService.findByPK(teamId);
			if (pubgTeam == null) {
				result.setMessage("战队不存在！");
				return result;
			}
			
			// 验证队员与战队的关系
			Query query = new Query();
			query.put("USER_ID", userId);
			query.put("TEAM_ID", pubgTeam.getRowId());
			query.put("RELATION_STATE", PubgConstant.USER_TEAM_RELATION_STATE_2);
			PubgUserTeam pubgUserTeam = this.pubgUserTeamService.find(query);
			if (pubgUserTeam == null) {
				result.setMessage("您还未加入该战队！");
				return result;
			}
			
			// 验证比赛是否存在
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(matchId);
			if (pubgMatch == null) {
				result.setMessage("赛事不存在！");
			    return result;
			}
			
			// 验证是否已经加入
			query = new Query();
			query.put("USER_ID", userId);
			query.put("MATCH_ID", pubgMatch.getRowId());
			query.put("_IN$USER_STATE", UserMatchConstant.USER_MATCH_10.getId() + ", " + UserMatchConstant.USER_MATCH_20.getId());
			List<PubgUserMatch> pubgUserMatchList = this.pubgUserMatchService.findList(query);
			for (PubgUserMatch pubgUserMatch : pubgUserMatchList) {
				if (UserMatchConstant.USER_MATCH_10.getId().equals(pubgUserMatch.getUserState())) {
					result.setMessage("您已经申请该赛事，请勿重复申请！");
					return result;
				} else if (UserMatchConstant.USER_MATCH_20.getId().equals(pubgUserMatch.getUserState())) {
					result.setMessage("您的申请已经通过！");
					return result;
				}
			}
			
			// 验证赛事的状态
			if (!(MatchConstant.MATCH_STATE_30.getId() + "").equals(pubgMatch.getMatchState())) {
				result.setMessage("当前赛事状态为【" + MatchConstant.findName(Integer.valueOf(pubgMatch.getMatchState())) + "】不可报名，！");
			    return result;
			}
			
			// 验证该战队是否有该赛事
			if (pubgMatch.getMatchTeamId() == null 
					|| pubgMatch.getMatchTeamId().indexOf(pubgTeam.getRowId() + ",") < 0) {
				result.setMessage("您当前加入的战队还未授权赛事！");
			    return result;
			}
			
			// 验证队员的余额是否充足
			if (pubgUserTeam.getUserTeamBalance() < pubgMatch.getApplyFee()) {
				result.setMessage("您当前所在战队的余额不足与参加比赛！");
				return result;
			}
			
			// 报名、更新队员的余额 等信息、生成财务流水
			this.pubgUserService.applyJoinMatch(pubgUserTeam, pubgMatch, pubgUser.getBalance());
			result.setCode(0);
			result.setMessage("申请成功！");
			
			// 记录操作日志
			this.pubgOperateLogService.insertUserOperateLog(Long.valueOf(userId), null, "申请加入比赛：" + pubgMatch.getMatchName());
		} catch (Exception e) {
			log.error("申请参加比赛出错！", e);
		}
		return result;
	}
	
	/**
	 * 更换邀请码
	 * 
	 * @author 朱建文 创建时间：2018年4月9日 下午6:46:15
	 */
	@ResponseBody
	@RequestMapping("/updateInviteCode")
	public Result<String> updateInviteCode(Long rowId, String inviteCode, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("申请参加比赛失败！");

		try {
			// 用户token状态
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}

			// 验证队员是否普通用户
			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			if (UserConstant.USER_ROLE_10.getId().equals(pubgUser.getUserRole())) {
				result.setMessage("您当前无权操作！");
				return result;
			}
			
			if (inviteCode == null) {
				inviteCode = RandomUtil.getRandomLeterAndNumber(6);
			}
			if (inviteCode == null || inviteCode.length() != 6) {
				result.setMessage("邀请码不能为空并且长度为6位的字母、数字组合！");
				return result;
			}
			
			if (rowId == null || rowId == 0) {
				result.setMessage("rowId为空！");
				return result;
			}
			
			this.pubgUserService.updateInvideCode(pubgUser, rowId, inviteCode);
			result.setCode(0);
			result.setData(inviteCode);
			result.setMessage("更换邀请码成功！");
		} catch (Exception e) {
			log.error("更换邀请码出错！", e);
		}
		return result;
	}

	/**
	 * 获取队员列表数据
	 * 
	 * @author 朱建文 创建时间：2018年4月4日 下午7:06:50
	 */
	@ResponseBody
	@RequestMapping("/getMemberList")
	public Result<Map<String, Object>> getMemberList(OPaging<Map<String, Object>> page, HttpServletRequest request){
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("获取队员列表数据失败！");
		try {
			
			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}
			
			// 当前用户是否是 队长
			PubgUser pubgUsser = this.pubgUserService.findByPK(Long.valueOf(optId));
			if (UserConstant.USER_ROLE_10.getId().equals(pubgUsser.getUserRole())) {
				result.setMessage("您无权获取数据！");
				return result;
			}
			page.getWm().put("non_userId", optId);
			
			// 是否需要按字母简拼分组
			String isGroupStr = getParamValueString(request, "isGroup", "false");
			boolean isGroup = Boolean.parseBoolean(isGroupStr);
			
			// 用户名称
			String userName = getParamValueString(request, "userName");
			if (userName != null && userName.length() > 0) {
				page.getWm().put("non_value", userName);
			}
			
			// 用户状态
			String userState = getParamValueString(request, "state");
			if (userState == null || userState.length() < 0) {
				userState = "1";
			}
			
			// 搜索用户不为空时，才能选择状态
			if (userName == null || userName.length() == 0) {
				page.getWm().put("a.RELATION_STATE", userState);
			}
			
			// 查询战队下的用户信息
			Map<String, Object> dataMap = pubgUserService.findMemberList(page, pubgUsser.getUserRole(), isGroup);
			if (dataMap == null || dataMap.isEmpty()) {
				result.setCode(0);
				result.setMessage("未获取到数据！");
				return result;
			}
			
			result.setData(dataMap);
			result.setCode(0);
			result.setMessage("获取队员列表数据成功！");
		} catch (Exception e) {
			log.error("获取队员列表数据出错！", e);
		}
		return result;
	}
	
	/**
	 * 队员详情
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 上午11:08:31
	 */
	@ResponseBody
	@RequestMapping("/memberDetail")
	public Result<Map<String, Object>> memberDetail(String token, Long rowId, HttpServletRequest request) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("队员详情失败！");
		try {
			String userId = tokenHandler.getCommUserInfoByToken(token);
            if (userId == null || userId.trim().length() == 0) {
                result.setCode(-2);
                result.setMessage("请重新登陆！");
                return result;
            }
            
            // 当前用户是否是 队长
 			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
 			if (UserConstant.USER_ROLE_10.getId().equals(pubgUser.getUserRole())) {
 				result.setMessage("您无权获取数据！");
 				return result;
 			}
            
            Map<String, Object> data = this.pubgUserService.getMemberDetail(pubgUser.getUserRole(), rowId);
            String userAccount = data.get("userAccount").toString();
            data.put("userAccount", userAccount.subSequence(0, 3) + "****" + userAccount.substring(8));
            result.setData(data);
            result.setCode(0);
            result.setMessage("获取队员详情成功！");
		} catch (Exception e) {
			log.error("队员详情出错！", e);
		}
		return result;
	}
	
	/**
	 * 获取资金明细（详细记录）
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午1:49:31
	 */
	@ResponseBody
	@RequestMapping("/userFinanceDetail")
	public Result<List<PubgFinanceFlowDetail>> userFinanceDetail(OPaging<PubgFinanceFlowDetail> page, HttpServletRequest request) {
		Result<List<PubgFinanceFlowDetail>> result = new Result<List<PubgFinanceFlowDetail>>();
		result.setCode(-1);
		result.setMessage("获取详细记录失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			PubgUser pubgUser = this.pubgUserService.findByPK(Long.valueOf(userId));
			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			columns.put("TRADE_TYPE_ID", "tradeTypeId");
			columns.put("TRADE_TYPE_NAME", "tradeTypeName");
			columns.put("CLUB_NAME", "clubName");
			columns.put("TEAM_NAME", "teamName");
			columns.put("USER_ACCOUNT", "userAccount");
			columns.put("TRADE_MONEY", "tradeMoney");
			columns.put("TRADE_MONEY_AFTER", "tradeMoneyAfter");
			columns.put("RELATION_ORDER_NO", "relationOrderNo");
			columns.put("IN_OUT_FLAG", "inOutFlag");
			columns.put("CREATE_TIME", "createTime");

			page.getWm().put("USER_ID", pubgUser.getRowId());
			Paging<PubgFinanceFlowDetail> pageTemp = pubgFinanceFlowDetailService.findPage(columns,page);
			result.setData(pageTemp.getDataList());
			result.setCode(0);
			result.setMessage("获取详细记录成功！");
		} catch (Exception e) {
			log.error("获取详细记录出错！", e);
		}
		return result;
	}
}
